﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RepertorySystem.Models;
using PagedList;

namespace RepertorySystem.Controllers {
    [Authorize]
    public class AccountListsController : Controller {
        private AccountListDbContext db = new AccountListDbContext();

        // GET: AccountLists
        public ActionResult Index() {

            //在分页前先要是用OrderBy或者OrderByDescending对数据进行正序或者倒序然后在skip（）跳过多少条，take（）查询多少条。
            //db.AccountLists.OrderBy(u => u.ID).Skip(0).Take(5).ToList();
            //List<AccountList> accountList = db.AccountLists.ToList();
            int arryLength = db.AccountLists.Count();
            int totalPages;
            if (arryLength % 5 != 0) {
                totalPages = (arryLength / 5) + 1;
            } else {
                totalPages = (arryLength / 5);
            }

            List<AccountList> content = db.AccountLists.OrderByDescending(u => u.Time).Skip(0).Take(5).ToList();
            ViewBag.content = content;
            ViewBag.totalPages = totalPages;
            ViewBag.currentPage = 1;

            return View();

        }
       

        //GET:AccountLists/GetNext/3
        public ActionResult GetNext(int currentPage) {
            int arryLength = db.AccountLists.Count();
            int totalPages;
            if (arryLength % 5 != 0) {
                totalPages = (arryLength / 5) + 1;
            } else {
                totalPages = (arryLength / 5);
            }

            List<AccountList> content = db.AccountLists.OrderByDescending(u => u.Time).Skip((currentPage-1) * 5).Take(5).ToList();
            ViewBag.content = content;
            ViewBag.currentPage = currentPage;
            ViewBag.totalPages = totalPages;
            return View("Index");

        }

        public ActionResult FindOne(String book_Name) {
            //查询数据
            this.TempData["book_Name"] = book_Name;
            //跳转
            return RedirectToAction("FindOneAccountList", "BookModels", "");
           
        }

        public ActionResult ReturnOne() {
            BookModels book = new BookModels();
            book =  this.TempData["resultBook"] as BookModels;
            int id = book.ID;

            List<AccountList> accountList =  db.AccountLists.Where(a => a.Book_Id == book.ID).ToList();


            ViewBag.content = accountList;
            ViewBag.currentPage = 1;
            ViewBag.totalPages = 1;


            return View("Index");
        }

        public ActionResult ReturnNoFind() {
          
            ViewBag.content = null;
            ViewBag.currentPage = 0;
            ViewBag.totalPages = 0;
            return View("Index");
        }

        // GET: AccountLists/Details/5
        public ActionResult Details(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            AccountList accountList = db.AccountLists.Find(id);
            if (accountList == null) {
                return HttpNotFound();
            }
            return View(accountList);
        }


        public ActionResult AccountCount() {

            //查找到所有数据
            //List<AccountList> list =  db.AccountLists.ToList();
            
            //查找到月份
            var q = db.AccountLists.GroupBy(t => new { Year = t.Time.Year, Month = t.Time.Month });
            var result = q.Select(t => new { Keys = t.Key.Year + "-" + (t.Key.Month.ToString().Length >= 2 ? t.Key.Month.ToString() : "0" + t.Key.Month.ToString()) }).ToList();
            

            int i = 1;
            
            List<Count> counts = new List<Count>();
            foreach (var item in result) {
                String[] dates = item.Keys.Split('-');
                int year = int.Parse(dates[0]);
                int month = int.Parse(dates[1]);
                String tim;
                if (month < 10) {
                    tim = "" + year + "-0" + month;
                }
                tim = "" + year + "-" + month;
                var temp = db.AccountLists.Where(us => us.Time.Year == year).ToList();
                List<AccountList> sumList =  temp.Where(na => na.Time.Month == month).ToList();
                //List<AccountList> sumList = db.AccountLists.SqlQuery("select * from dbo.AccountLists where Time LIKE "+item.Keys+"%").ToList();
                int sumPrices = 0;
                foreach (AccountList acc in sumList) {
                    sumPrices += acc.Price;
                }
                Count count = new Count();
                count.Id = i;
                count.time = item.Keys;
                count.sumPrice = sumPrices;
                counts.Add(count);
                i++;
            }

            ViewBag.content = counts;  
                   
            return View("Count");
        }

        // GET: AccountLists/Create
        public ActionResult Create() {
            if (this.TempData != null) {
                AccountList accountLists = this.TempData["accountList"] as AccountList;
                //添加新账目
                AccountList newaccountList = new AccountList();
                newaccountList.Time = accountLists.Time;
                newaccountList.Category = accountLists.Category;
                newaccountList.Book_Id = accountLists.Book_Id;
                newaccountList.Book_Number = accountLists.Book_Number;
                newaccountList.Price = accountLists.Price;
                //保存数据
                db.AccountLists.Add(newaccountList);
                db.SaveChanges();
                if (accountLists.Price > 0) {
                    return RedirectToAction("Create", "OutputStorages", "");
                } else {
                    return RedirectToAction("Create", "InputStorages", "");
                }

            }
            return View("Index");
        }

        // POST: AccountLists/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Time,Category,Book_Id,Book_Number,Price")] AccountList accountList) {
            if (ModelState.IsValid) {
                db.AccountLists.Add(accountList);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(accountList);
        }

        // GET: AccountLists/Edit/5
        public ActionResult Edit(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            AccountList accountList = db.AccountLists.Find(id);
            if (accountList == null) {
                return HttpNotFound();
            }
            return View(accountList);
        }

        // POST: AccountLists/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Time,Category,Book_Id,Book_Number,Price")] AccountList accountList) {
            if (ModelState.IsValid) {
                db.Entry(accountList).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(accountList);
        }

        // GET: AccountLists/Delete/5
        public ActionResult Delete(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            AccountList accountList = db.AccountLists.Find(id);
            if (accountList == null) {
                return HttpNotFound();
            }
            return View(accountList);
        }

        // POST: AccountLists/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id) {
            AccountList accountList = db.AccountLists.Find(id);
            db.AccountLists.Remove(accountList);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing) {
            if (disposing) {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
